#-------------------------------------------------------------------------------
# Name:        SaveWidget
# Purpose:
#
# Author:      Pablo
#
# Created:     03/09/2013
# Copyright:   (c) Monxcleyr Productions 2013
# Licence:     GPL v3
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import pygame, logging, os, cPickle, zlib
import label

class SaveWidget():

  """class comment"""

  def __init__(self, surface, pos, namefont, detailsfont, fontcolor, widget, widgethover, widgetblocked, clicksound, hoversound, blockedsound, soundsystem, settings, save):
    self.surface = surface
    self.namefont = namefont
    self.detailsfont = detailsfont
    self.fontcolor = fontcolor
    self.widget = pygame.image.load('resources/graphics/' + widget).convert_alpha()
    self.pos = (pos[0] - self.widget.get_width() / 2, pos[1])
    self.widgethover = pygame.image.load('resources/graphics/' + widgethover).convert_alpha()
    self.widgetblocked = pygame.image.load('resources/graphics/' + widgetblocked).convert_alpha()
    self.clicksound = clicksound
    self.hoversound = hoversound
    self.blockedsound = blockedsound
    self.soundsystem = soundsystem
    self.settings = settings
    self.save = save
    self.rect = self.widget.get_rect()
    self.rect.topleft = self.pos
    self.prevhover = False
    self.blocked = False
    self.selected = False

    self.loadSave()

    pos = (self.pos[0] + self.widget.get_width() / 2, self.pos[1] + 10)
    self.namelabel = label.Label(self.surface, ' ', pos, 'center', self.namefont, self.fontcolor)
    pos = (self.pos[0] + 10, self.pos[1] + 5)
    self.slotlabel = label.Label(self.surface, 'Slot ' + str(self.save), pos, 'left', self.detailsfont, self.fontcolor)
    pos = (self.pos[0] +10, self.pos[1] + self.widget.get_height() - self.detailsfont.size('Time Played')[1] - 5)
    self.timelabel = label.Label(self.surface, 'Time Played:', pos, 'left', self.detailsfont, self.fontcolor)
    pos = (self.pos[0] -10 + self.widget.get_width(), self.pos[1] + self.widget.get_height() - self.detailsfont.size('Time Played')[1] - 5)
    self.detaillabel = label.Label(self.surface, ' ', pos, 'right', self.detailsfont, self.fontcolor)



  def draw(self, mouse, mode='load'):

    if mode is 'load':
      if not self.hasfile:
        self.blocked = True
    elif mode is 'namedialog' or mode is 'newoverwrite' or mode is 'saveoverwrite':
      mouse = [(0,0),0,0,0,0,0]
    elif mode is 'new':
      self.blocked = False

    if self.error and mode is not 'new':
      self.blocked = True

    self.selected = False
    # draw the different states of sprites
    if self.rect.collidepoint(mouse[0]):
      if not self.blocked:
        self.surface.blit(self.widgethover, self.pos)
      if self.prevhover == False and not self.blocked:
        self.soundsystem.play(self.hoversound, self.settings)
        self.prevhover = True
      if mouse[1] == 1 and not self.blocked:
        self.selected = True
        self.soundsystem.play(self.clicksound, self.settings)
      elif mouse[1] == 1 and self.blocked:
        self.soundsystem.play(self.blockedsound, self.settings)
    else:
      self.prevhover = False

    if not self.blocked:
      self.surface.blit(self.widget, self.pos)
    else:
      self.surface.blit(self.widgetblocked, self.pos)


    self.namelabel.setText(self.name)
    self.timelabel.setText('Time Played: ' + str(self.timeplayed))
    self.detaillabel.setText(self.detail)
    if not self.hasfile:
      self.timelabel.setText(' ')
      self.detaillabel.setText(' ')
    self.namelabel.draw()
    self.slotlabel.draw()
    self.timelabel.draw()
    self.detaillabel.draw()



  def loadSave(self):

    self.error = False
    self.hasfile = False
    if os.path.isfile(os.path.join('Saves/' + str(self.save) + '.sav')):
      self.hasfile = True
      try:
        f = open(os.path.join('Saves/', str(self.save) + '.sav'),'rb')
        obj = cPickle.load(f)
        self.world = cPickle.loads(zlib.decompress(obj))
        f.close()
        logging.info('Game slot %s initiated', self.save)
      except:
        self.error = True
        logging.critical('Failed to initiate saveslot %s' % self.save)
    else:
      logging.info('No existing save for slot %s' % self.save)


    if self.hasfile and not self.error:
      #load up the stats of the save, if it is avaliable and isn't broken
      self.name = self.world.savename
      runtime = self.world.timeplayed
      self.detail = self.world.detail

      minutes = runtime / 60
      seconds = runtime - (minutes * 60)
      hours = minutes / 60
      if hours > 0:
        minutes = minutes - hours * 60
      if seconds < 10:
        seconds = '0' + str(seconds)
      if minutes < 10:
        minutes = '0' + str(minutes)
      self.timeplayed = str(hours) + ':' + str(minutes) + ':' + str(seconds)

    elif self.error:
      # load up some generic stats instead
      self.name = 'CORRUPTED SAVE'
      self.timeplayed = '00:00:00'
      self.detail = ' '

    else:
      self.name = 'UNUSED SAVE'
      self.timeplayed = '00:00:00'
      self.detail = ' '

    self.world = None


  def reset(self):
    self.selected = 0
